<template>
  <view class="poster-container">
    <view class="poster-modal" v-if="showPoster">
      <view class="poster-content">
        <!-- 调整画布尺寸为 630rpx*820rpx -->
        <canvas canvas-id="posterCanvas" class="poster-canvas"></canvas>
        
        <view class="btn-group">
          <button class="save-btn" @tap="saveImage">保存图片</button>
          <button class="cancel-btn" @tap="closePoster">取消</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      showPoster: false,
      canvasWidth: 630, // rpx
      canvasHeight: 880, // rpx
      pixelRatio: 1,
    }
  },
  
  props: {
    goodsInfo: {
      type: Object,
      default: () => ({
        image: '',
        title: '',
        price: '',
        qrcode: ''
      })
    }
  },
  
  methods: {
    showPosterModal() {
      this.showPoster = true
      this.$nextTick(() => {
        this.drawPoster()
      })
    },
    
    closePoster() {
      this.showPoster = false
    },
    
    async drawPoster() {
      const ctx = uni.createCanvasContext('posterCanvas', this)
      this.pixelRatio = uni.getSystemInfoSync().pixelRatio
      
      // 计算实际尺寸
      const width = this.canvasWidth / 750 * uni.getSystemInfoSync().windowWidth
      const height = this.canvasHeight / 750 * uni.getSystemInfoSync().windowWidth
      
      // 绘制白色背景
      ctx.fillStyle = '#ffffff'
      ctx.fillRect(0, 0, width, height)
      
      try {
        // 绘制商品图片（占据上半部分，高度为总高度的60%）
        await this.drawImage(ctx, this.goodsInfo.image, 0, 0, width, height * 0.74)
        
        // 绘制商品标题（最多两行，字体稍微调小）
        ctx.setFontSize(13)
        ctx.setFillStyle('#333333')
        const title = this.goodsInfo.title
        const titleWidth = width * 0.65 // 预留右侧小程序码空间
        const titleLines = this.splitText(ctx, title, titleWidth)
        titleLines.slice(0, 2).forEach((line, index) => {
          ctx.fillText(line, 15, height * 0.84 + (index * 18))
        })
        
        // 绘制价格（调整位置和大小）
        ctx.setFontSize(18)
        ctx.setFillStyle('#ff4444')
        ctx.fillText(`¥${this.goodsInfo.price}`, 15, height * 0.84 + 45)
        
        // 绘制小程序码（调整大小和位置）
        const qrcodeSize = width * 0.25
        await this.drawImage(
          ctx,
          this.goodsInfo.qrcode,
          width - qrcodeSize - 15,
          height * 0.78,
          qrcodeSize,
          qrcodeSize
        )
        
        ctx.draw(false, () => {
          console.log('海报绘制完成')
        })
        
      } catch (error) {
        console.error('绘制海报失败:', error)
        uni.showToast({
          title: '生成海报失败',
          icon: 'none'
        })
      }
    },
    
    drawImage(ctx, url, x, y, width, height) {
      return new Promise((resolve, reject) => {
        uni.getImageInfo({
          src: url,
          success: (image) => {
            ctx.drawImage(image.path, x, y, width, height)
            resolve()
          },
          fail: reject
        })
      })
    },
    
    splitText(ctx, text, maxWidth) {
      const lines = []
      let line = ''
      
      for (let char of text) {
        const testLine = line + char
        const metrics = ctx.measureText(testLine)
        
        if (metrics.width > maxWidth) {
          lines.push(line)
          line = char
        } else {
          line = testLine
        }
      }
      
      lines.push(line)
      return lines
    },
    
    saveImage() {
      uni.canvasToTempFilePath({
        canvasId: 'posterCanvas',
        success: (res) => {
          uni.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              uni.showToast({
                title: '保存成功',
                icon: 'success'
              })
              this.closePoster()
            },
            fail: () => {
              uni.showToast({
                title: '保存失败',
                icon: 'none'
              })
            }
          })
        },
        fail: () => {
          uni.showToast({
            title: '生成图片失败',
            icon: 'none'
          })
        }
      }, this)
    }
  }
}
</script>

<style lang="scss" scoped>
.poster-container {
  .poster-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
    
    .poster-content {
      width: 630rpx; // 调整为较小的尺寸
      box-sizing: border-box;
      
      .poster-canvas {
        width: 630rpx; // 调整画布宽度
        height: 880rpx; // 调整画布高度
        background: #ffffff;
      }
      
      .btn-group {
        display: flex;
        justify-content: space-between;
        margin-top: 30rpx;
        
        button {
          width: 260rpx; // 调整按钮宽度
          height: 76rpx;
          line-height: 76rpx;
          text-align: center;
          border-radius: 38rpx;
          font-size: 28rpx;
          
          &.save-btn {
            background: #020202;
            color: #ffffff;
          }
          
          &.cancel-btn {
            background: #f5f5f5;
            color: #333333;
          }
        }
      }
    }
  }
}
</style>